{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>智能体配置 - {{ agent.name }} - 数据源管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" />
    <style>
      .sidebar {
        height: 100vh;
        background-color: #343a40;
        color: white;
        padding-top: 20px;
      }
      .sidebar .nav-link {
        color: #adb5bd;
        border-radius: 0;
      }
      .sidebar .nav-link.active {
        background-color: #0d6efd;
        color: white;
      }
      .content {
        padding: 20px;
      }
      .form-group {
        margin-bottom: 1.5rem;
      }
      .table-selection {
        max-height: 400px;
        overflow-y: auto;
        border: 1px solid #e9ecef;
        border-radius: 0.25rem;
        padding: 1rem;
      }
      .table-item {
        margin-bottom: 1rem;
        border: 1px solid #dee2e6;
        border-radius: 0.25rem;
        overflow: hidden;
      }
      .table-header {
        background-color: #f8f9fa;
        padding: 0.75rem 1rem;
        border-bottom: 1px solid #dee2e6;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .table-fields {
        padding: 0.75rem 1rem;
      }
      .field-item {
        margin-left: 1.5rem;
        display: flex;
        align-items: center;
        margin-bottom: 0.5rem;
      }
      .badge {
        font-size: 0.75rem;
        margin-left: 0.5rem;
      }
      .required::after {
        content: "*"; 
        color: red;
        margin-left: 5px;
      }
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-2 d-none d-md-block sidebar">
          <div class="text-center mb-4">
            <h3>数据管理</h3>
          </div>
          <ul class="nav flex-column">
            <li class="nav-item">
              <a class="nav-link" href="{% url 'datasource_list' %}">
                <i class="bi bi-database me-2"></i>
                数据源管理
              </a>
            </li>
            <li class="nav-item">
              <a class="nav-link active" href="{% url 'agent_management' %}">
                <i class="bi bi-robot me-2"></i>
                智能体管理
              </a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="{% url 'operation_log' %}">
                <i class="bi bi-clock-history me-2"></i>
                操作日志
              </a>
            </li>
          </ul>
        </div>

        <!-- 主内容区 -->
        <main class="col-md-10 ms-sm-auto px-md-4 content">
          <!-- 顶部导航 -->
          <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
            <div class="container-fluid">
              <a href="{% url 'agent_management' %}" class="btn btn-outline-secondary me-2">
                <i class="bi bi-arrow-left me-1"></i>
                返回列表
              </a>
              <h4 class="mb-0">配置智能体: {{ agent.name }}</h4>
              <div class="d-flex ms-auto gap-2">
                <button class="btn btn-outline-secondary me-2">
                  <i class="bi bi-play me-1"></i>
                  立即执行
                </button>
                <button class="btn btn-outline-secondary">
                  <i class="bi bi-person me-1"></i>
                  登录
                </button>
              </div>
            </div>
          </nav>

          <!-- 配置卡片 -->
          <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">智能体基本配置</h5>
            </div>
            <div class="card-body">
              <form method="post">
                {% csrf_token %}
                <input type="hidden" name="agentId" value="{{ agent.id }}" />

                <div class="form-group">
                  <label for="agentName" class="required">智能体名称</label>
                  <input type="text" class="form-control" id="agentName" name="agentName" value="{{ agent.name }}" required />
                </div>

                <div class="form-group">
                  <label for="agentDescription">智能体描述</label>
                  <textarea class="form-control" id="agentDescription" name="agentDescription" rows="3">{{ agent.description }}</textarea>
                </div>

                <div class="form-group">
                  <label for="datasourceSelect" class="required">关联数据源</label>
                  <select class="form-select" id="datasourceSelect" name="datasourceId" required>
                    <option value="">请选择数据源</option>
                    {% for datasource in datasources %}
                    <option value="{{ datasource.id }}" {% if datasource.id == agent.datasource_id %}selected{% endif %}>{{ datasource.name }} ({{ datasource.engine }})</option>
                    {% endfor %}
                  </select>
                </div>

                <div class="form-group">
                  <label class="required">执行方式</label>
                  <div class="form-check mb-2">
                    <input class="form-check-input" type="radio" name="executionType" id="manualExecution" value="manual" {% if agent.schedule_type == None %}checked{% endif %} />
                    <label class="form-check-label" for="manualExecution">手动执行</label>
                  </div>
                  <div class="form-check mb-2">
                    <input class="form-check-input" type="radio" name="executionType" id="scheduledExecution" value="scheduled" {% if agent.schedule_type %}checked{% endif %} />
                    <label class="form-check-label" for="scheduledExecution">定时执行</label>
                  </div>
                </div>

                <div class="form-group" id="scheduleConfig" style="display: {% if agent.schedule_type %}block{% else %}none{% endif %};">
                  <label for="scheduleType" class="required">调度类型</label>
                  <select class="form-select" id="scheduleType" name="scheduleType">
                    <option value="interval" {% if agent.schedule_type == 'interval' %}selected{% endif %}>间隔执行</option>
                    <option value="cron" {% if agent.schedule_type == 'cron' %}selected{% endif %}>Cron表达式</option>
                  </select>

                  <div id="intervalConfig" style="display: {% if agent.schedule_type == 'interval' %}block{% else %}none{% endif %}; margin-top: 15px;">
                    <div class="row">
                      <div class="col-md-6">
                        <label for="intervalValue" class="required">间隔值</label>
                        <input type="number" class="form-control" id="intervalValue" name="intervalValue" placeholder="请输入间隔值" min="1" value="1" />
                      </div>
                      <div class="col-md-6">
                        <label for="intervalUnit" class="required">时间单位</label>
                        <select class="form-select" id="intervalUnit" name="intervalUnit">
                          <option value="minutes">分钟</option>
                          <option value="hours">小时</option>
                          <option value="days" selected>天</option>
                          <option value="weeks">周</option>
                        </select>
                      </div>
                    </div>
                  </div>

                  <div id="cronConfig" style="display: {% if agent.schedule_type == 'cron' %}block{% else %}none{% endif %}; margin-top: 15px;">
                    <label for="cronExpression" class="required">Cron表达式</label>
                    <input type="text" class="form-control" id="cronExpression" name="cronExpression" value="{{ agent.schedule_expression }}" placeholder="例如: 0 0 * * * 表示每天午夜执行" />
                    <small class="form-text text-muted mt-1">Cron表达式格式: 分钟 小时 日期 月份 星期</small>
                  </div>
                </div>

                <div class="form-group">
                  <label for="destinationAgent" class="required">目标智能体</label>
                  <input type="text" class="form-control" id="destinationAgent" name="destinationAgent" value="{{ agent.destination_agent }}" required />
                  <small class="form-text text-muted mt-1">数据抽取后发送到的目标智能体</small>
                </div>

                <div class="form-group">
                  <label class="required">字段选择</label>
                  <div class="table-selection" id="tableSelectionSection">
                    <!-- 表和字段将通过JavaScript动态生成 -->
                    <div class="text-center text-muted py-5" id="loadingIndicator">
                      <div class="spinner-border text-primary mb-2" role="status"></div>
                      <div>加载表和字段信息中...</div>
                    </div>
                  </div>
                </div>

                <div class="d-flex justify-content-end gap-2 mt-4">
                  <button type="button" class="btn btn-outline-secondary" onclick="window.location.href='{% url 'agent_management' %}'">取消</button>
                  <button type="submit" class="btn btn-primary">保存配置</button>
                </div>
              </form>
            </div>
          </div>
        </main>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        // 执行方式切换
        document.querySelectorAll('input[name="executionType"]').forEach(radio => {
          radio.addEventListener('change', function() {
            if (this.value === 'scheduled') {
              document.getElementById('scheduleConfig').style.display = 'block';
            } else {
              document.getElementById('scheduleConfig').style.display = 'none';
            }
          });
        });

        // 调度类型切换
        document.getElementById('scheduleType').addEventListener('change', function() {
          if (this.value === 'interval') {
            document.getElementById('intervalConfig').style.display = 'block';
            document.getElementById('cronConfig').style.display = 'none';
          } else {
            document.getElementById('intervalConfig').style.display = 'none';
            document.getElementById('cronConfig').style.display = 'block';
          }
        });

        // 模拟加载表和字段信息
        setTimeout(function() {
          const container = document.getElementById('tableSelectionSection');
          container.innerHTML = '';

          // 模拟表数据
          const tables = [
            {
              name: 'users',
              fields: [
                { name: 'id', type: 'int', selected: true },
                { name: 'name', type: 'varchar', selected: true },
                { name: 'email', type: 'varchar', selected: true },
                { name: 'password', type: 'varchar', selected: false },
                { name: 'created_at', type: 'datetime', selected: false }
              ]
            },
            {
              name: 'products',
              fields: [
                { name: 'id', type: 'int', selected: false },
                { name: 'name', type: 'varchar', selected: false },
                { name: 'price', type: 'decimal', selected: false },
                { name: 'description', type: 'text', selected: false }
              ]
            }
          ];

          // 渲染表和字段
          tables.forEach(table => {
            const tableItem = document.createElement('div');
            tableItem.className = 'table-item';

            // 表标题
            const tableHeader = document.createElement('div');
            tableHeader.className = 'table-header';
            tableHeader.innerHTML = `
              <div>
                <input type="checkbox" id="table_${table.name}" class="table-checkbox" ${table.fields.every(f => f.selected) ? 'checked' : ''}>
                <label for="table_${table.name}">${table.name}</label>
              </div>
              <span class="badge bg-secondary">${table.fields.length}个字段</span>
            `;
            tableItem.appendChild(tableHeader);

            // 字段列表
            const tableFields = document.createElement('div');
            tableFields.className = 'table-fields';
            table.fields.forEach(field => {
              const fieldItem = document.createElement('div');
              fieldItem.className = 'field-item';
              fieldItem.innerHTML = `
                <input type="checkbox" id="field_${table.name}_${field.name}" name="exposed_fields" value="${table.name}.${field.name}" ${field.selected ? 'checked' : ''}>
                <label for="field_${table.name}_${field.name}">${field.name} <span class="text-muted">(${field.type})</span></label>
              `;
              tableFields.appendChild(fieldItem);
            });
            tableItem.appendChild(tableFields);

            container.appendChild(tableItem);
          });

          // 添加表复选框事件
          document.querySelectorAll('.table-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
              const tableName = this.id.replace('table_', '');
              document.querySelectorAll(`input[id^="field_${tableName}_"]`).forEach(fieldCheckbox => {
                fieldCheckbox.checked = this.checked;
              });
            });
          });
        }, 1000);
      });
    </script>
  </body>
</html>